﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using UnityEngine;
using KBEngine;

namespace KBE_HotFix.UI
{
    public class MainUI : UIHandler
    {
        public string stringAccount = "";
        public bool startRelogin = false;
        public int ui_state = 0;

        public MainUI()
        {
            installEvents();
        }

        void installEvents()
        {
            // common
            KBE_HotFix.Event.registerOut("onKicked", this, "onKicked");
            KBE_HotFix.Event.registerOut("onDisconnected", this, "onDisconnected");
            KBE_HotFix.Event.registerOut("onConnectionState", this, "onConnectionState");

            // login
            KBE_HotFix.Event.registerOut("onCreateAccountResult", this, "onCreateAccountResult");
            KBE_HotFix.Event.registerOut("onLoginFailed", this, "onLoginFailed");
            KBE_HotFix.Event.registerOut("onVersionNotMatch", this, "onVersionNotMatch");
            KBE_HotFix.Event.registerOut("onScriptVersionNotMatch", this, "onScriptVersionNotMatch");
            KBE_HotFix.Event.registerOut("onLoginBaseappFailed", this, "onLoginBaseappFailed");
            KBE_HotFix.Event.registerOut("onLoginSuccessfully", this, "onLoginSuccessfully");
            KBE_HotFix.Event.registerOut("onReloginBaseappFailed", this, "onReloginBaseappFailed");
            KBE_HotFix.Event.registerOut("onReloginBaseappSuccessfully", this, "onReloginBaseappSuccessfully");
            KBE_HotFix.Event.registerOut("onLoginBaseapp", this, "onLoginBaseapp");
            KBE_HotFix.Event.registerOut("Loginapp_importClientMessages", this, "Loginapp_importClientMessages");
            KBE_HotFix.Event.registerOut("Baseapp_importClientMessages", this, "Baseapp_importClientMessages");
            KBE_HotFix.Event.registerOut("Baseapp_importClientEntityDef", this, "Baseapp_importClientEntityDef");
        }

        public void onLoginBtnClick(GameObject go)
        {
            var accountGo = GameObject.Find("UI Root/Root/Center/Login(Clone)/Login_Ctrls/Account_Input");
            var passwordGo = GameObject.Find("UI Root/Root/Center/Login(Clone)/Login_Ctrls/Password_Input");
            if (accountGo == null || passwordGo == null)
            {
                Dbg.ERROR_MSG("cant find controll of accountInput and passwordInput");
                return;
            }

            var account = accountGo.GetComponent<UIInput>().value;
            var password = passwordGo.GetComponent<UIInput>().value;
            login(account, password);
        }

        public void onRegisterBtnClick(GameObject go)
        {
            var accountGo = GameObject.Find("UI Root/Root/Center/Login(Clone)/Login_Ctrls/Account_Input");
            var passwordGo = GameObject.Find("UI Root/Root/Center/Login(Clone)/Login_Ctrls/Password_Input");
            if (accountGo == null || passwordGo == null)
            {
                Dbg.ERROR_MSG("cant find controll of accountInput and passwordInput");
                return;
            }
            var account = accountGo.GetComponent<UIInput>().value;
            var password = passwordGo.GetComponent<UIInput>().value;
            createAccount(account, password);
        }

        public void onCreateAvatarConfirmClick(GameObject go)
        {
            var input = UIObject.Center.transform.Find("CreateAvatar/Background/NameInput").GetComponent<UIInput>();
            Event.fireIn("reqCreateAvatr", input.value);
        }

        public void info(string msg)
        {
            Debug.Log(msg);
        }

        public void err(string msg)
        {
            Debug.LogError(msg);
        }

        public void login(string account, string password)
        {
            stringAccount = account;
            info("connect to server...(连接到服务端...)");
            KBEngine.Event.fireIn("login", account, password, System.Text.Encoding.UTF8.GetBytes("kbengine_unity3d_demo"));
        }

        public void createAccount(string account, string password)
        {
            stringAccount = account;
            info("connect to server...(连接到服务端...)");

            KBEngine.Event.fireIn("createAccount", account, password, System.Text.Encoding.UTF8.GetBytes("kbengine_unity3d_demo"));
        }

        public void onCreateAccountResult(UInt16 retcode, byte[] datas)
        {
            if (retcode != 0)
            {
                err("createAccount is error(注册账号错误)! err=" + KBEngineApp.app.serverErr(retcode));
                return;
            }

            if (KBEngineApp.validEmail(stringAccount))
            {
                info("createAccount is successfully, Please activate your Email!(注册账号成功，请激活Email!)");
            }
            else
            {
                info("createAccount is successfully!(注册账号成功!)");
            }
        }

        public void onConnectionState(bool success)
        {
            if (!success)
                err(" (连接错误)");
            else
                info("connect successfully, please wait...(连接成功，请等候...)");
        }

        public void onLoginFailed(UInt16 failedcode)
        {
            if (failedcode == 20)
            {
                err("login is failed(登陆失败), err=" + KBEngineApp.app.serverErr(failedcode));
            }
            else
            {
                err("login is failed(登陆失败), err=" + KBEngineApp.app.serverErr(failedcode));
            }
        }

        public void onVersionNotMatch(string verInfo, string serVerInfo)
        {
            err("");
        }

        public void onScriptVersionNotMatch(string verInfo, string serVerInfo)
        {
            err("");
        }

        public void onLoginBaseappFailed(UInt16 failedcode)
        {
            err("loginBaseapp is failed(登陆网关失败), err=" + KBEngineApp.app.serverErr(failedcode));
        }

        public void onLoginBaseapp()
        {
            info("connect to loginBaseapp, please wait...(连接到网关， 请稍后...)");
        }

        public void onReloginBaseappFailed(UInt16 failedcode)
        {
            err("relogin is failed(重连网关失败), err=" + KBEngineApp.app.serverErr(failedcode));
            startRelogin = false;
        }

        public void onReloginBaseappSuccessfully()
        {
            info("relogin is successfully!(重连成功!)");
            startRelogin = false;
        }

        public void onLoginSuccessfully(UInt64 rndUUID, Int32 eid, object accountEntity)
        {
            info("login is successfully!(登陆成功!)");
        }

        public void onKicked(UInt16 failedcode)
        {
            err("kick, disconnect!, reason=" + KBEngineApp.app.serverErr(failedcode));
            //SceneManager.LoadScene("login");
            //ui_state = 0;
        }

        public void Loginapp_importClientMessages()
        {
            info("Loginapp_importClientMessages ...");
        }

        public void Baseapp_importClientMessages()
        {
            info("Baseapp_importClientMessages ...");
        }

        public void Baseapp_importClientEntityDef()
        {
            info("importClientEntityDef ...");
        }

        public void onDisconnected()
        {
            err("disconnect! will try to reconnect...(你已掉线，尝试重连中!)");
            startRelogin = true;

            //Invoke("onReloginBaseappTimer", 1.0f);
            ILRTPlugins.ILRTMain.Ins.DoCoroutine(startReloginBaseapp(1.0f));
        }

        System.Collections.IEnumerator startReloginBaseapp(float delay)
        {
            yield return new WaitForSeconds(1.0f);
            onReloginBaseappTimer();
        }

        public void onReloginBaseappTimer()
        {
            if (ui_state == 0)
            {
                err("disconnect! (你已掉线!)");
                return;
            }

            KBEngineApp.app.reloginBaseapp();
            //if (startRelogin)
            //  Invoke("onReloginBaseappTimer", 3.0f);
            if (startRelogin)
                ILRTPlugins.ILRTMain.Ins.DoCoroutine(startReloginBaseapp(3.0f));
        }
    }
}
